package com.sencorsta.ids.game.openHandler;

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.MsgService;
import com.sencorsta.ids.common.service.MysqlServiceS;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.game.db.TradeRecord;
import com.sencorsta.ids.game.db.Wallet;
import com.sencorsta.ids.game.proto.GamePushRobMoneyByProto;
import com.sencorsta.ids.game.proto.GameRobAllByProto;
import com.sencorsta.ids.game.util.PushAndSaved;
import com.sencorsta.ids.game.world.bean.Player;
import com.sencorsta.ids.game.world.bean.World;
import com.sencorsta.ids.game.world.game.Game;
import com.sencorsta.ids.game.world.pak.*;
import com.sencorsta.ids.game.world.room.*;
import com.sencorsta.utils.string.StringUtil;
import io.netty.channel.Channel;

import java.util.Date;

/**
 * @author TAO
 * @description: 抢所有红包
 * @date 2019/12/1 18:40
 */
@ClientEvent("RobAllRedPackage")
public class RobAllRedPackage extends OpenMessageHandler implements RedisService {
    @Override
    public RpcMessage request(Channel channel, JSONObject jsonObject, String s, byte[] bytes, byte[] protobuf) {
        String userIds = userId;
        Out.debug("执行方法: ---->RobAllRedPackage--------- 抢所有红包:", userIds);
        GameRobAllByProto.RobAllRes.Builder res = GameRobAllByProto.RobAllRes.newBuilder();

        try {
            GameRobAllByProto.RobAllReq req = GameRobAllByProto.RobAllReq.parseFrom(protobuf);
            int roomId = req.getRoomId();//得到加入的房间房间Id
            String rpId = req.getRpId();//得到抢的红包Id
            int gameId = req.getGameId();//得到游戏Id
            //1.判断玩家是否存在
            if (StringUtil.isEmpty(userIds)) {
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.GAME_IS_NULL));
                return responseProto(res);
            }
            Player player=World.getInstance().allPlayers.get(userIds);
            if (player==null) {
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.GAME_IS_NULL));
                return responseProto(res);
            }

            //2.判断游戏是否存在
            Game game = World.getInstance().games.get(gameId);
            if (game == null) {//游戏不存在
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.GAME_IS_NULL));
                return responseProto(res);
            }
            //判断房间是否存在
            Room room=game.rooms.get(roomId);
            if (room == null) {//游戏不存在
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.ROOM_IS_NULL));
                return responseProto(res);
            }
            RedPackage redPackage = room.rpPackage.get(rpId);
            if (redPackage == null) {//红包不存在
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.PACKET_IS_NULL));
                return responseProto(res);
            }

            if (!room.zoneUsers.keySet().contains(userIds)) {
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.PLAYER_IS_NO_ROOM));
                return responseProto(res);
            }
            JSONObject rpResule = redPackage.rpResult;//得到当前红包记录
            if (rpResule != null) {
                if (rpResule.keySet().size() != 0&&rpResule.keySet().contains(userIds)) {
                    if (userIds.equals(redPackage.sendUserId)) {
                        if (redPackage.isRobedBySend == false&&World.NIUNIU==gameId) {
                            //发包者第一次抢放行
                        } else {
                            Out.debug("该红包你以领取过__", "这个傻逼用户是__", userIds);
                            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.RED_PACKET_IS_GET));
                            return responseProto(res);
                        }
                    } else {
                        Out.debug("该红包你以领取过__", "这个傻逼用户是__", userIds);
                        res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.RED_PACKET_IS_GET));
                        return responseProto(res);
                    }
                }
            }
            long robDeposit = redPackage.robDeposit;//得到当前包的押金
            Out.debug("robDeposit==>", robDeposit);
            if (gameId!=World.WELFARE){//福利玩法不需要
                if (player.amount < robDeposit) {
                    res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.AMOUNT_NOT_ENOUGH));
                    return responseProto(res);
                }
            }

            switch (gameId) {
                case World.SAOLEI:
                    //发扫雷包者自己不能自己抢
                    if (userIds.equals(redPackage.sendUserId)) {
                        res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SEND_PACKAGE_IS_NOT_ROB));
                        return responseProto(res);
                    }
                    break;
                case World.NIUNIU:
                    if (player.userId.equals(redPackage.sendUserId) && !redPackage.isRobedBySend) {
                        redPackage.isRobedBySend = true;
                        JSONObject jsonObjectNiuNiu = rpResule.getJSONObject(userIds);
                        GamePushRobMoneyByProto.PushRobMoney.Builder push = GamePushRobMoneyByProto.PushRobMoney.newBuilder();
                        push.setGameId(World.NIUNIU);
                        push.setRoomId(roomId);
                        push.setRpId(rpId);
                        push.setMoney(jsonObjectNiuNiu.getLong("amount"));
                        Out.debug("牛牛即将为==》", player.userId, "__推送__");
                        MsgService.pushBySID(PushAndSaved.pushProto(player.userId, "push.RobMoney", push), player.SID);
                        res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
                        return responseProto(res);

                    }
                    Out.debug("-----------牛牛抢红包--update-----------");
                    if (redPackage.count == 1 && !rpResule.containsKey(redPackage.sendUserId) && !player.userId.equals(redPackage.sendUserId)) {
                        Out.debug("发包者还没有抢包");
                        res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.REDPACKAGE_IS_END));
                        return responseProto(res);
                    }

                    break;
                case World.JINGQIANG:
                    //发扫雷包者自己不能自己抢
                    if (userIds.equals(redPackage.sendUserId)) {
                        res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SEND_PACKAGE_IS_NOT_ROB_JINQIANG));
                        return responseProto(res);
                    }
                    break;
                case World.LONGHU:
                    //发扫雷包者自己不能自己抢
                    if (userIds.equals(redPackage.sendUserId)) {
                        res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SEND_PACKAGE_IS_NOT_ROB_LONGHU));
                        return responseProto(res);
                    }
                    break;
                case World.WELFARE:
                    //机器人不判流水...玩家判断流水
                    if (player.type==1){//是玩家
                        long runWater=TradeRecord.getRunWater(player.userId);
                        if (runWater<robDeposit){//今日流水小于抢包流水不可抢（这里的robDeposit在发包时就已经替换成最小抢包流水金额）
                            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.RUNWATER_NOT_ENOUGH));
                            return responseProto(res);
                        }
                    }
                    break;
                case World.JIELONG:
                    //接龙可以自己抢
                    break;
            }
            if (redPackage.count == 0 || redPackage.status != 0) {//判断红包数量
                Out.debug("红包已抢完");
                res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.REDPACKAGE_IS_END));
                return responseProto(res);
            }
            room.addEvent(() -> {
                redPackage.rob(player);
            });

            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR));
            return responseProto(res);
        }

    }

}
